//
//  MapViewController.m
//  LanQiuQuan
//
//  Created by TonyGenius on 16/3/24.
//  Copyright © 2016年 Rip. All rights reserved.
//

#import "MapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <MAMapView.h>
#import "Marco.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "CustomAnnotationView.h"


@interface MapViewController ()<MAMapViewDelegate, AMapSearchDelegate>
{
    XMTabBarController *_tab;
    AMapSearchAPI *_search;
    AMapReGeocodeSearchRequest *_regoRequest;
    NSString *_cityCode;
    NSString *_provice;
    MAPointAnnotation *_pointView;
}

//@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (nonatomic, strong) MAMapView *mapView;

@property (weak, nonatomic) IBOutlet UIButton *playButton;

@property (weak, nonatomic) IBOutlet UILabel *distanceLab;

@property (weak, nonatomic) IBOutlet UILabel *numberLab;

@property (weak, nonatomic) IBOutlet UILabel *statusLab;

@property (weak, nonatomic) IBOutlet UIScrollView *playerScorllView;

@property (weak, nonatomic) IBOutlet UIButton *moreBtn;
@property (nonatomic, assign) NSInteger selectField;
@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //配置用户信息
    _selectField = 100;
    [MAMapServices sharedServices].apiKey = kMAMAPAPPKEY;
    [AMapSearchServices sharedServices].apiKey = kMAMAPAPPKEY;

     [self initSearch];
    [self initMapView];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    
    backItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backItem;
    self.navigationItem.title = @"附近的球场";
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"moreField"] style:UIBarButtonItemStyleDone target:self action:@selector(displayMuchField:)];
    rightItem.tag = 101;
    [rightItem setTintColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    _tab = (XMTabBarController *)self.tabBarController;
    [_tab xmTabBarHidden:YES animated:YES];
}

- (IBAction)displayMoreField:(UIButton *)sender {
    _selectField = sender.tag;
    [self initPlaygroundModle];
}

- (void)initSearch
{
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    
}

- (void)displayMuchField:(UIBarButtonItem *)item
{
    _selectField = item.tag;
    [self initPlaygroundModle];
}

- (void)displaySelectField
{
     _pointView = [[MAPointAnnotation alloc] init];
    _pointView.coordinate = _location.coordinate;
    _pointView.title = _addressName;
    _pointView.subtitle = _addName;
    [_mapView addAnnotation:_pointView];
}

- (void)initPlaygroundModle
{
    [_mapView removeAnnotation:_pointView];
    NSLog(@"%@",_cityCode);
    NSString *url = [NSString stringWithFormat:@"%@/%@",kURLFORCITYPLAYGROUNDLIST,_cityCode];
    [NetWorkEngin getRequestWithParametes:url andBody:nil andFinishBlock:^(NSDictionary *respondData, NSError *error) {

        _playgroundList = [jsonHelper jsonForPlayGroundWithDictionary:respondData];
        for (int i = 0; i < _playgroundList.count; i ++) {
            PlayGroundModel *model = _playgroundList[i];
            NSArray *array = [model.location componentsSeparatedByString:@","];
            CLLocationCoordinate2D coordinate = {[array[1] floatValue],[array[0] floatValue]};
            
            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            pointAnnotation.coordinate = coordinate;
            
            pointAnnotation.title = model.name;
            pointAnnotation.subtitle = model.address;
            [_mapView addAnnotation:pointAnnotation];
        }
        
    }];

}

- (void)initMapView
{
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    [self.view addSubview:_mapView];
    [self.view sendSubviewToBack:_mapView];
    _mapView.delegate = self;
    
//    _mapView.rotateEnabled= NO;
    
    
    //开启定位
    _mapView.showsUserLocation = YES;
    
    [_mapView setUserTrackingMode:MAUserTrackingModeFollow];
    [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -AMapSearchDelegate
//实现逆地理编码的回调函数
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if(response.regeocode != nil)
    {
        //通过AMapReGeocodeSearchResponse对象处理搜索结果
        NSString *result = [NSString stringWithFormat:@"ReGeocode: %@", response.regeocode];
        NSLog(@"ReGeo: %@", result);
        NSLog(@"%@,城市编码:%@",response.regeocode.addressComponent.city,response.regeocode.addressComponent.citycode);
        _cityCode = response.regeocode.addressComponent.citycode;
        _provice = response.regeocode.addressComponent.province;
        NSLog(@"城市代码%@,省／直辖市%@",_cityCode,_provice);
    }
//    [self initPlaygroundModle];
    
    [self displaySelectField];
    
}

#pragma mark -MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        //取出当前位置的坐标
        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        if (!_regoRequest) {
            _regoRequest = [[AMapReGeocodeSearchRequest alloc] init];
            _regoRequest.location = [AMapGeoPoint locationWithLatitude:userLocation.coordinate.latitude longitude:userLocation.coordinate.longitude];
            _regoRequest.requireExtension = YES;
            [_search AMapReGoecodeSearch: _regoRequest];
        }
    }
}
- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation;
{
//        NSLog(@"%s",__func__);
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"annotationReuseIndetifier";
        
        CustomAnnotationView *customAnnotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        customAnnotationView.selected = NO;
        
        if (customAnnotationView == nil)
        {
            customAnnotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        if (_selectField == 100) {
            customAnnotationView.calloutOffset = CGPointMake(0, -50);
            customAnnotationView.image = [UIImage imageNamed:@"mapPoint"];
            customAnnotationView.canShowCallout= NO;       //设置气泡可以弹出，默认为NO
            customAnnotationView.centerOffset = CGPointMake(0, -18);
            [customAnnotationView setSelected:YES animated:YES];
            MAPointAnnotation *point = annotation;
            customAnnotationView.calloutView.title = point.title;
            customAnnotationView.calloutView.subtitle = point.subtitle;
        }
        else
        {
            customAnnotationView.calloutOffset = CGPointMake(0, -50);
            customAnnotationView.image = [UIImage imageNamed:@"mapPoint"];
            customAnnotationView.canShowCallout= NO;       //设置气泡可以弹出，默认为NO
            customAnnotationView.centerOffset = CGPointMake(0, -18);
//            [customAnnotationView setSelected:YES animated:YES];
        }
        return customAnnotationView;
    }
    return nil;
}



- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    NSLog(@"11111111111111%@",view);
    view.selected = YES;
}


- (IBAction)goToPlayBasketball:(id)sender {
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
